package cn.lanqiao.facelogin.interceptors;

import cn.lanqiao.facelogin.domain.ResParameter;
import cn.lanqiao.facelogin.domain.Result;
import cn.lanqiao.facelogin.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//        获取请求头中令牌
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("token");
        try {
            JwtUtil.verify(token);
            return true;
        } catch (Exception e) {
            map.put("state", false);
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }
    }
}
